from django.shortcuts import render
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response

from goods.models import SKU, GoodsCategory
from goods.serializers import SKUSerializer, SKUIndexSerializer


# GET /skus/search/?text=<搜索关键字>
class SKUSearchViewSet(HaystackViewSet):
    # 指定索引类对应模型类
    index_models = [SKU]

    # 指定搜索结果序列化时所使用的序列化器类
    # 搜索结果中每个对象都包含两个属性：
    # text: 索引字段的内容
    # object: 从数据库中搜索出模型对象（此处是SKU模型对象)
    serializer_class = SKUIndexSerializer

# GET /categories/(?P<category_id>\d+)/skus?page=xxx&page_size=xxx&ordering=xxx
class SKUListView(ListAPIView):
    # 思考为什么自己写的只会返回数据不会分页,继承mixin类就会分页
    filter_backends = [OrderingFilter]
    ordering_fields = ('create_time', 'price', 'sales')
    serializer_class = SKUSerializer
    def get_queryset(self):
        category_id = self.kwargs['category_id']
        skus = SKU.objects.filter(category_id=category_id)
        return skus
    # def get(self, request, category_id):
    #     skus= self.get_queryset()
    #     serializer = self.get_serializer(skus, many=True)
    #     return Response(serializer.data)
